//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by mac on 16/3/15.
//  Copyright © 2016年 hw.chow. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    //获取授权的token方法
     func loadAccessToken(code: String,finished: (isSuccess: Bool) -> () ){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        let AFN = AFHTTPSessionManager()
        
        //设置支持解析纯文本的json格式的数据
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            
            //类型转换  将anyObject对象，转换为字典数组对象 [key : value]
            guard let dict = result as? [String:AnyObject]else{
                
                print("数据格式不合法")
                //执行失败的回调
                finished(isSuccess: false)
                return
            }
            
            
            //程序走到这里代表 anyObject 一定被转换为字典格式的数据
            let account = UserAccount(dict: dict)
            print(account)
            //获取用户信息
            self.loadUserInfo(account,finished: finished)
            
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print(error)
        }
    }
    //MARK:加载用户信息
    private func loadUserInfo(account: UserAccount,finished: (isSuccess: Bool) -> () ){
        
        //         print(access_token,uid)
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        
        let AFN = AFHTTPSessionManager()
        //程序员承诺parameters一定有值
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            print(result)
            //获取用户信息数据
            guard let dict = result as? [String: AnyObject] else{
                
                print("数据格式不合法")
                finished(isSuccess: false)
                return
            }
            
            //我们需要的用户信息就全部获取到
            let name = dict["name"] as! String
            let avatar_large = dict["avatar_large"] as! String
            
            account.name = name
            account.avatar_large = avatar_large
            print(account)
            //调用保存的用户信息
            account.saveAccount()
            //执行成功的回调
            finished(isSuccess: true)
            
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print(error)
        }
    }

}
